package controlador;

import java.io.IOException;
import java.util.List;

import com.google.appengine.api.datastore.Key;
import javax.jdo.PersistenceManager;
import javax.jdo.Query;

public class controladorJdo<T> {
	
	private Class<T> clase;
	
	public static <T> controladorJdo<T> getInstance(Class<T> clase)
	{
		return new controladorJdo<T> (clase);
	}
	
	protected controladorJdo(Class<T> clase)
	{
		this.clase = clase;
	}
	
	public void insert(T objeto)
	{
		final PersistenceManager pm = PMF.get().getPersistenceManager();
		try{
			pm.currentTransaction().begin();
			pm.makePersistent(objeto);
			pm.currentTransaction().commit();
		}finally{
			if(pm.currentTransaction().isActive())
				pm.currentTransaction().rollback();
			pm.close();
		}
	}
	
	public void update (T objeto)
	{
		final PersistenceManager pm = PMF.get().getPersistenceManager();
		try{
			pm.currentTransaction().begin();
			pm.makePersistent(objeto);
			pm.currentTransaction().commit();
		}finally{
			if(pm.currentTransaction().isActive())
				pm.currentTransaction().rollback();
			pm.close();
		}
	}
	
	public void delete (Key key)
	{
		final PersistenceManager pm = PMF.get().getPersistenceManager();
		try{
			pm.currentTransaction().begin();
			T objetoViejo = clase.cast(pm.getObjectById(key,false));
			pm.deletePersistent(objetoViejo);
			pm.currentTransaction().commit();
		}finally{
			if(pm.currentTransaction().isActive())
				pm.currentTransaction().rollback();
			pm.close();
		}
	}
	
	@SuppressWarnings("unchecked")
	public List<T> finAll()
	{
		final PersistenceManager pm = PMF.get().getPersistenceManager();
		final Query query =pm.newQuery(clase);
		List<T> resultado = (List<T>) query.execute();
		pm.close();
		return resultado;
	}
	
	@SuppressWarnings("unchecked")
	public List<T> findAllByParameter (String parametro, String tipo, Object valor)throws IOException 
	{
		final PersistenceManager pm = PMF.get().getPersistenceManager();
		Query query = pm.newQuery(parametro+" == param");
		query.declareParameters(tipo+" param");
		List<T> resultado = (List<T>) query.execute(valor);
		pm.close();
		if(resultado.size()< 1){throw new IOException ("El objeto no fue encontrado");}
		return (resultado.size()==0)? null:resultado;		
	}
	
	public T findByKey (Key key)
	{
		final PersistenceManager pm = PMF.get().getPersistenceManager();
		T objeto = pm.getObjectById(clase,key);
		pm.close();
		return objeto;
	}
}
